import React, { useMemo, useState } from 'react';
import { Card, Form, Input, Select, Button, Table, Tag, Space, Modal, InputNumber, message, Switch } from 'antd';
import { MobileOutlined, PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';

const { Option } = Select;

export default function UVPhoneModels() {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [editOpen, setEditOpen] = useState(false);
  const [editingRow, setEditingRow] = useState(null);

  const [data, setData] = useState(() => (
    Array.from({ length: 12 }).map((_, i) => ({
      id: 1000 + i,
      brand: i % 3 === 0 ? 'Apple' : (i % 3 === 1 ? 'Huawei' : 'Xiaomi'),
      model: i % 3 === 0 ? `iPhone ${12 + (i % 4)}` : (i % 3 === 1 ? `Mate ${30 + i}` : `Mi ${10 + i}`),
      dpi: 300 + (i * 10),
      uvCompatible: i % 2 === 0,
      createTime: `2025-02-${(i % 28) + 1} 10:00:00`,
    }))
  ));

  const columns = useMemo(() => ([
    { title: 'ID', dataIndex: 'id', width: 100 },
    { title: '品牌', dataIndex: 'brand', width: 140 },
    { title: '型号', dataIndex: 'model', width: 180 },
    { title: 'DPI', dataIndex: 'dpi', width: 100 },
    {
      title: 'UV兼容', dataIndex: 'uvCompatible', width: 120,
      render: (val, row) => (
        <Switch
          checked={!!val}
          onChange={(checked) => {
            row._loading = true;
            setData((ds) => ds.map(it => it.id === row.id ? { ...it, uvCompatible: checked } : it));
            message.success('已更新UV兼容状态');
            row._loading = false;
          }}
        />
      )
    },
    { title: '创建时间', dataIndex: 'createTime', width: 180 },
    {
      title: '操作', dataIndex: 'actions', fixed: 'right', align: 'right', width: 220,
      render: (_, row) => (
        <Space>
          <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(row)}>编辑</Button>
          <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(row)}>删除</Button>
        </Space>
      )
    },
  ]), []);

  const handleSearch = async () => {
    const values = await form.validateFields().catch(() => null);
    if (!values) return;
    setLoading(true);
    setTimeout(() => {
      setData(prev => prev.filter(item => {
        const byBrand = values.brand ? item.brand?.toLowerCase().includes(values.brand.toLowerCase()) : true;
        const byModel = values.model ? item.model?.toLowerCase().includes(values.model.toLowerCase()) : true;
        const byDpi = values.dpi ? Number(item.dpi) === Number(values.dpi) : true;
        const byUV = values.uvCompatible === undefined ? true : item.uvCompatible === (values.uvCompatible === '1');
        return byBrand && byModel && byDpi && byUV;
      }));
      setLoading(false);
    }, 300);
  };

  const resetSearch = () => {
    form.resetFields();
    setData(Array.from({ length: 12 }).map((_, i) => ({
      id: 1000 + i,
      brand: i % 3 === 0 ? 'Apple' : (i % 3 === 1 ? 'Huawei' : 'Xiaomi'),
      model: i % 3 === 0 ? `iPhone ${12 + (i % 4)}` : (i % 3 === 1 ? `Mate ${30 + i}` : `Mi ${10 + i}`),
      dpi: 300 + (i * 10),
      uvCompatible: i % 2 === 0,
      createTime: `2025-02-${(i % 28) + 1} 10:00:00`,
    })));
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  const openEdit = (row) => {
    setEditingRow(row || null);
    setEditOpen(true);
  };

  const addModel = () => openEdit(null);

  const handleEditSubmit = (values) => {
    if (editingRow) {
      setData(prev => prev.map(d => (d.id === editingRow.id ? { ...d, ...values, dpi: Number(values.dpi || d.dpi), uvCompatible: values.uvCompatible === '1' } : d)));
      message.success('编辑成功');
    } else {
      const newId = Math.max(...data.map(d => d.id)) + 1;
      setData(prev => [{
        id: newId,
        brand: values.brand || 'Unknown',
        model: values.model || `型号-${newId}`,
        dpi: Number(values.dpi || 300),
        uvCompatible: values.uvCompatible === '1',
        createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      }, ...prev]);
      message.success('新增成功');
    }
    setEditOpen(false);
  };

  const handleDelete = (row) => {
    Modal.confirm({
      title: '确认删除',
      content: `将删除型号 ${row.brand} ${row.model}`,
      onOk: () => {
        setData(prev => prev.filter(d => d.id !== row.id));
        message.success('删除成功');
      },
    });
  };

  return (
    <div style={{ padding: 16 }}>
      <Card
        title={<Space><MobileOutlined />设备管理 - UV手机型号管理</Space>}
        extra={(
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={addModel}>新增型号</Button>
            <Button danger disabled={!selectedRowKeys.length} onClick={() => {
              Modal.confirm({
                title: '批量删除',
                content: `确定删除选中的 ${selectedRowKeys.length} 条型号？`,
                onOk: () => {
                  setData(prev => prev.filter(d => !selectedRowKeys.includes(d.id)));
                  setSelectedRowKeys([]);
                  message.success('批量删除成功');
                },
              });
            }}>批量删除</Button>
          </Space>
        )}
        style={{ marginBottom: 16 }}
      >
        <Form form={form} layout="inline" style={{ rowGap: 12 }}>
          <Form.Item name="brand" label="品牌">
            <Input placeholder="请输入品牌" allowClear />
          </Form.Item>
          <Form.Item name="model" label="型号">
            <Input placeholder="请输入型号" allowClear />
          </Form.Item>
          <Form.Item name="dpi" label="DPI">
            <InputNumber placeholder="精度" min={1} style={{ width: 120 }} />
          </Form.Item>
          <Form.Item name="uvCompatible" label="UV兼容">
            <Select allowClear placeholder="全部" style={{ width: 120 }}>
              <Option value="1">是</Option>
              <Option value="0">否</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space style={{ marginLeft: 8, }}>
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch} style={{ height: 36 }}>查询</Button>
              <Button icon={<ReloadOutlined />} onClick={resetSearch} style={{ height: 36 }}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          loading={loading}
          rowSelection={rowSelection}
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 编辑/新增型号 */}
      <Modal
        title={editingRow ? '编辑UV手机型号' : '新增UV手机型号'}
        open={editOpen}
        destroyOnClose
        onCancel={() => setEditOpen(false)}
        onOk={() => {
          const formId = 'uv-model-edit-form';
          const formEl = document.getElementById(formId);
          if (formEl) {
            const values = Object.fromEntries(new FormData(formEl).entries());
            handleEditSubmit(values);
          }
        }}
      >
        <form id="uv-model-edit-form">
          <Space direction="vertical" style={{ width: '100%' }}>
            <Input name="brand" defaultValue={editingRow?.brand} placeholder="品牌" />
            <Input name="model" defaultValue={editingRow?.model} placeholder="型号" />
            <InputNumber name="dpi" defaultValue={editingRow?.dpi} placeholder="DPI" min={1} style={{ width: '100%' }} />
            <Select defaultValue={editingRow?.uvCompatible ? '1' : '0'} style={{ width: '100%' }} name="uvCompatible">
              <Option value="1">UV兼容</Option>
              <Option value="0">不兼容</Option>
            </Select>
          </Space>
        </form>
      </Modal>
    </div>
  );
}